import os
import configparser
from datetime import timedelta

import redis
import sys
import logging


def get_config():
    """获取配置文件"""
    conf = configparser.ConfigParser()
    flask_env = os.environ.get("FLASK_ENV")

    base_path = os.path.dirname(os.path.abspath(__file__)) + "/"
    config_file = f"{base_path}{flask_env}.ini"

    if not os.path.exists(config_file):
        raise Exception(f"config file not exist {config_file}")

    conf.read(config_file)
    logging.getLogger(__name__).info(f"加载配置文件完成 {config_file}")
    return conf


class BaseConfig:
    """配置基类"""

    SECRET_KEY = "ShaHeTop-Almighty-ares"  # session加密
    PERMANENT_SESSION_LIFETIME = timedelta(days=30)  # 设置session过期时间
    DEBUG = True
    RUN_HOST = "0.0.0.0"
    RUN_PORT = 9999

    @staticmethod
    def init_app(app):
        pass


class AppConfig(BaseConfig):
    """区分配置文件"""

    conf = get_config()  # 根据环境变量获取对应的配置文件

    FLASK_PYDANTIC_VALIDATION_ERROR_RAISE = True
    # base
    SECRET_KEY = conf.get("base", "SECRET_KEY")  # session加密
    PERMANENT_SESSION_LIFETIME = timedelta(days=30)  # 设置session过期时间
    DEBUG = conf.getboolean("base", "DEBUG")
    RUN_HOST = conf.get("base", "RUN_HOST")
    RUN_PORT = conf.getint("base", "RUN_PORT")

    UPLOAD_FOLDER = conf.get("base", "UPLOAD_FOLDER")
    ALLOWED_EXTENSIONS = set(["txt", "pdf", "png", "jpg", "jpeg", "gif"])

    # sqlite
    sqlite_dir = (
        f"sqlite:///{os.getcwd() + os.path.sep + 'db' +os.path.sep }open_essay.db"
    )
    logging.info(f"sqlite数据库文件位置{sqlite_dir}")
    DB_URI = sqlite_dir
    SQLALCHEMY_DATABASE_URI = DB_URI
    SQLALCHEMY_TRACK_MODIFICATIONS = True
    SQLALCHEMY_ECHO = False
